<?php

namespace App\Http\Controllers\Plugin;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

trait OcrController
{
    public function __construct()
    {
        $oss = config('aliyun.web');
        AlibabaCloud::accessKeyClient($oss['accessKeyId'], $oss['accessKeySecret'])
            ->regionId('cn-shanghai')
            ->asDefaultClient();
    }

    public function getHeadImg($imgUrl){
        try {
            $data = cache()->remember($imgUrl, 30, function ()use($imgUrl){
                $result = AlibabaCloud::rpc()
                    ->product('ocr')
                    // ->scheme('https') // https | http
                    ->version('2019-12-30')
                    ->action('RecognizeIdentityCard')
                    ->method('POST')
                    ->host('ocr.cn-shanghai.aliyuncs.com')
                    ->options([
                        'query' => [
                            'RegionId' => "cn-shanghai",
                            'ImageURL' => $imgUrl,
                            'Side' => "face",
                        ],
                    ])
                    ->request();
                return $result->toArray();
            });
            return $data;

        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
